﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json.Converters;
using System.Data;
using System.Text;
using DBUtility;
using System.IO;
using System.Configuration;

namespace YiDaShuiHang
{
    public partial class get_data : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                get();
            }
        }


        public void get()
        {
            string type = "";
            string username = "";
            string password = "";
            string pagecurrent = "";
            string indexwhere = "";
            string poststr = getpost();
            string page = "";
            string page1 = "";
            string code = "";
            string value = "";
            string dormcombolist_id = "";
            string bind_data = "";
            string addormcombo_value = "";
            string dormcombolist_value = "";
            string where = "1=1";
            string xiugai_content = "";
            int page_current=1;
            int record_count = 0;
            int allcount=1;
            if (!string.IsNullOrEmpty(poststr))
            {
                JObject jobj = JObject.Parse(poststr);
                type = jobject(jobj, "type");
                username = jobject(jobj, "username");
                password = jobject(jobj, "password");
                code = jobject(jobj, "code");
                pagecurrent = jobject(jobj, "pagecurrent");
                indexwhere = jobject(jobj, "indexwhere");
                value = jobject(jobj,"value");
                xiugai_content = jobject(jobj,"xiugai_content");
                bind_data = jobject(jobj, "bind_data");
                addormcombo_value = jobject(jobj, "addormcombo_value");
                dormcombolist_value = jobject(jobj, "dormcombolist_value");
                page = jobject(jobj, "pagecurrent");
                dormcombolist_id = jobject(jobj, "dormcombolist_id");
                page1 = jobject(jobj, "page1");
                int.TryParse(page, out page_current);

            }

            string returnstr = "";
            try
            {
                switch (type.ToLower())
                {
                    case "login"://登入页面
                        #region
                        string login_result = commen.login(username,password);
                        if (login_result.Contains("OK"))
                        {
                            returnstr = "{\"result\":\"ok\",\"msg\":\"成功\"}";
                        }
                        else {
                            returnstr = "{\"result\":\"error\",\"msg\":\"失败\"}";
                        }
                        #endregion
                        break;
                    case "getbuywater":
                        string checkresult = "";
                       // commen.log(code);
                        DataTable taocan_list = commen.gettable_clientlist(code);
                       
                        if (taocan_list.Rows.Count != 0)
                        {
                            string area = taocan_list.Rows[0][2].ToString();
                            string building = taocan_list.Rows[0][3].ToString();
                            string drom = taocan_list.Rows[0][4].ToString();
                            checkresult =  area + "|" + building + "|" + drom;
                            returnstr = "{\"result\":\"ok\",\"msg\":\"" + checkresult + "\"}";
                           // commen.log(returnstr);
                        }
                        else
                        {
                            checkresult = "你的手机没有绑定,请到绑定页面先绑定！";
                            returnstr = "{\"result\":\"not\",\"msg\":\"" + checkresult + "\"}";
                        }
                       
                        break;
                    case "input_taocan":
                        string input_taocan_str = commen.user_addDormcombo(code);
                        returnstr = "{\"result\":\"ok\",\"msg\":\"" + input_taocan_str + "\"}";
                        break;
                    case"get_manager":
                    #region
                        where += "  and state=0 ";
                        DataTable manager_dt = commen.get_manager(page_current, where,ref allcount);
                        returnstr = "{\"result\":\"ok\",\"msg\":\"成功\",\"record_count\":\"" + allcount + "\",\"page_curent\":\"" + page_current + "\",\"table\":" + DataTableToJson(manager_dt) + "}";
                    #endregion
                    break;
                    case "delete_manager":
                    #region
                        DBUtility.commen.delete_manager(page1);
                        where += "  and state=0 ";
                        DataTable manager_dwt = commen.get_manager(page_current, where,ref allcount);
                        returnstr = "{\"result\":\"ok\",\"msg\":\"成功\",\"record_count\":\"" + allcount + "\",\"page_curent\":\"" + page_current + "\",\"table\":" + DataTableToJson(manager_dwt) + "}";
                 
                   #endregion
                    break;
                    case "change_pwd":
                    #region
                    string statue=  commen.changge_pwd(username, password);
                    returnstr = "{\"result\":\"ok\",\"msg\":\"" + statue + "\"}";
                    #endregion
                    break;
                    case"addmanager":
                    #region
                   string addmanager= commen.addmanager(username, password);
                   returnstr = "{\"result\":\"ok\",\"msg\":\"" + addmanager + "\"}";
                    #endregion
                    break;
                    case "get_index":
                    #region
                    DataTable dt = commen.indexdata(page_current, indexwhere, ref record_count);
                    returnstr = "{\"result\":\"ok\",\"msg\":\"成功\",\"record_count\":\"" + record_count + "\",\"page_curent\":\"" + page_current + "\",\"table\":" + DataTableToJson(dt) + "}";
                    #endregion
                     break;
                    case "index_delect":
                     #region
                     string index_delectstr = commen.index_delect(dormcombolist_id);
                     if (index_delectstr == "ok")
                     {
                         DataTable index_delect_dt = commen.indexdata(page_current, indexwhere, ref record_count);
                         returnstr = "{\"result\":\"ok\",\"msg\":\"成功\",\"record_count\":\"" + record_count + "\",\"page_curent\":\"" + page_current + "\",\"table\":" + DataTableToJson(index_delect_dt) + "}";
                     }
                     else
                     {
                         returnstr = "{\"result\":\"error\",\"msg\":\"" + index_delectstr + "\"}";
                     }
                     #endregion
                     break;
                    case "dormcombolist":
                     DataTable dorm_dt = commen.dormcombolist(page_current, indexwhere, ref record_count);
                     returnstr = "{\"result\":\"ok\",\"msg\":\"成功\",\"record_count\":\"" + record_count + "\",\"page_curent\":\"" + page_current + "\",\"table\":" + DataTableToJson(dorm_dt) + "}";
                    
                     break;
                    case "outbinds":
                    string outbinds_str= commen.bindout(code);
                    returnstr = "{\"result\":\"ok\",\"msg\":\"" + outbinds_str + "\"}";
                     break;
                    case "addrecord":
                     #region
                     string [] value_arry=value.Split('|');
                        DataTable addrecord_ = commen.check_caocan(value);
                        if (addrecord_.Rows.Count!=0) {
                            int name = int.Parse(value_arry[0]);
                            int fd=int.Parse(addrecord_.Rows[0][6].ToString());
                            if (fd < name)
                            {
                                returnstr = "{\"result\":\"short\",\"msg\":\"叫水桶数不能多于宿舍剩余桶数！\"}";
                            }
                            else {
                                string addrecord_str = commen.addrecord(value);
                                returnstr = "{\"result\":\"ok\",\"msg\":\"" + addrecord_str + "\"}";
                            }
                           
                        }
                        else {

                            returnstr = "{\"result\":\"null\",\"msg\":\"此宿舍没有购买套餐记录或者已经删除！\"}";
                        }
                        
                    #endregion
                     break;
                    case "addormcombo":
                     string str = commen.addDormcombo(addormcombo_value);
                     returnstr = "{\"result\":\"ok\",\"msg\":\"" + str + "\"}";
                     break;
                    case "dormcombolist_xiugai":
                     string dormcombolist_xiugaistr = commen.dormcombolist_xiugai(dormcombolist_value);
                     returnstr = "{\"result\":\"ok\",\"msg\":\"" + dormcombolist_xiugaistr + "\"}";
                     break;
                    case "dormcombolist_delect":
                     #region
                     string delectstr = commen.dormcombolist_delect(dormcombolist_id);
                     if (delectstr == "ok")
                     {
                         DataTable dormcombolist_delect_dt = commen.dormcombolist(page_current, indexwhere, ref record_count);
                         returnstr = "{\"result\":\"ok\",\"msg\":\"成功\",\"record_count\":\"" + record_count + "\",\"page_curent\":\"" + page_current + "\",\"table\":" + DataTableToJson(dormcombolist_delect_dt) + "}";
                     }
                     else
                     {
                         returnstr = "{\"result\":\"error\",\"msg\":\"" + delectstr + "\"}";
                     }
                     #endregion
                     break;
                    case "clientlist":
                     string[] areey = indexwhere.Split('|');
                      
                     where +=  areey[0] ==""?"":" and area='" + areey[0] + "'";
                     where += areey[1] == "" ? "" : " and building='" + areey[1] + "'";
                     where += areey[2] == "" ? "" : " and drom='" + areey[2] + "'";
               
                     DataTable clientlist_dt = commen.clientlist(page_current, where+" and state=0 ", ref record_count);
                     returnstr = "{\"result\":\"ok\",\"msg\":\"成功\",\"record_count\":\"" + record_count + "\",\"page_curent\":\"" + page_current + "\",\"table\":" + DataTableToJson(clientlist_dt) + "}";
                    
                     break;
                    case "getopenid":
                     #region
                     string[] appid = System.Configuration.ConfigurationManager.AppSettings["appid_user"].Split('|');
                     string url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=" + appid[0] + "&secret=" + appid[1] + "&code=" + code + "&grant_type=authorization_code";
                     Web_Request net = new Web_Request(url, "GET");
                     string text = net.GetResponseText();
                     JObject jobj1 = JObject.Parse(text);
                     string openid = jobject(jobj1, "openid");
                     net.Dispose();
                     returnstr = "{\"result\":\"ok\",\"msg\":\"" + openid + "\"}";
                     #endregion
                     break;
                    case "bind_username":
                     string resultinset = commen.bindusername(bind_data);
                     returnstr = "{\"result\":\"ok\",\"msg\":\"" + resultinset + "\"}";
                     break;
                    case "getoutbind":
                     DataTable getoutbind_dt = commen.getbinddata(code);
                     returnstr = "{\"result\":\"ok\",\"msg\":\"成功\",\"table\":" + DataTableToJson(getoutbind_dt) + "}";

                     break;
                    case"getuser_record":
                     #region
                     string getuser_record_dt = commen.getuser_record(code);
                     if (getuser_record_dt.Contains("ok_have")) {
                         string[] getuser_record_data = getuser_record_dt.Split('|');
                         string area = " top 5 ";
                         DataTable record_askwater = commen.gettable_record_askwater(area, getuser_record_data[1], getuser_record_data[2]);
                         DataTable taocanlist = commen.gettable_taocanlist(getuser_record_data[0], getuser_record_data[1], getuser_record_data[2]);
                         returnstr = "{\"result\":\"ok\",\"msg\":\"成功\",\"record_askwater\":" + DataTableToJson(record_askwater) + ",\"taocanlist\":" + DataTableToJson(taocanlist) + "}";
                     }
                        else{
                            returnstr = "{\"result\":\"ok_null\",\"msg\":\"" + getuser_record_dt + "\"}";
                     }
                   #endregion
                     break;
                    case "showmore_askwater":
                     string[] getalluser_record_data = code.Split('|');
                     string showmore_askwater_area = "";
                     DataTable showmore_askwater_data = commen.gettable_record_askwater(showmore_askwater_area, getalluser_record_data[0], getalluser_record_data[1]);
                     returnstr = "{\"result\":\"ok\",\"msg\":\"成功\",\"record_askwater\":" + DataTableToJson(showmore_askwater_data) + "}";
                     break;
                    case "userask_water":
                     #region
                     string userask_water_ = commen.adduserask_water(code);
                    // commen.log(userask_water_);
                     if (userask_water_.Contains("添加成功"))
                     {
                     string[] userask_water_data = code.Split('|');
                        //上面是把叫水记录记录
                        //下面是获取数据到页面展示
                     string userask_water_area = " top 5 ";
                     DataTable userask_water_record_askwater = commen.gettable_record_askwater(userask_water_area, userask_water_data[2], userask_water_data[3]);
                     DataTable userask_water_taocanlist = commen.gettable_taocanlist(userask_water_data[0], userask_water_data[2], userask_water_data[3]);
                     returnstr = "{\"result\":\"ok\",\"msg\":\"叫水成功\",\"record_askwater\":" + DataTableToJson(userask_water_record_askwater) + ",\"taocanlist\":" + DataTableToJson(userask_water_taocanlist) + "}";
                        }
                        else{
                            returnstr = "{\"result\":\"error\",\"msg\":\"" + userask_water_ + "\"}";
                     }
                        
                 //  commen.log(returnstr);
                  #endregion
                     break;
                    case "ask_water_loaddowm":
                     string downpath = "";
                     #region
                       string[] arrey = code.Split('|');
                       DataTable loaddown = new DataTable();
                       if (arrey[0] != "全部" && arrey[0] != "")
                       {
                       loaddown = commen.ask_water_loaddowm(code);
                       downpath = DBUtility.OutExcel.GetExcelFiles_one_askwater(loaddown);
                       returnstr = "{\"result\":\"ok\",\"msg\":\"成功\",\"down_link\":\"" + downpath + "\"}";
                        }
                        else{
                            downpath = DBUtility.OutExcel.GetExcelFiles_all_askwater(code);
                            returnstr = "{\"result\":\"ok\",\"msg\":\"成功\",\"down_link\":\"" + downpath + "\"}";
                        }
                     #endregion
                     break;

                    case "dromlist_loaddowm":
                     #region
                     string[] dromlist_loaddowm_arrey = code.Split('|');
                     DataTable dromlist_loaddowm_dt = new DataTable();
                     if (dromlist_loaddowm_arrey[0] != "全部")
                       {

                           loaddown = commen.dromlist_loaddowm(code);
                           downpath = DBUtility.OutExcel.GetExcelFiles_one_dorm(loaddown);
                        returnstr = "{\"result\":\"ok\",\"msg\":\"成功\",\"down_link\":\"" + downpath + "\"}";
                        }
                        else{
                            downpath = DBUtility.OutExcel.GetExcelFiles_all_dorm(code);
                            returnstr = "{\"result\":\"ok\",\"msg\":\"成功\",\"down_link\":\"" + downpath + "\"}";
                       }

                     #endregion
                     break;
                    case "checkuser":
                     DataTable checkuser_dt = commen.getbinddata(code);
                     if (checkuser_dt.Rows.Count != 0)
                     {
                         returnstr = "{\"result\":\"have\"}";
                     }
                     else {
                         returnstr = "{\"result\":\"null\"}";
                     }
                     break;

                    case "xiugai_index":
                     string xiugai_index_str = commen.xiugai_content(xiugai_content);
                     returnstr = "{\"result\":\"ok\",\"msg\":\"" + xiugai_index_str + "\"}";

                     break;
                    case "outbind":
                     string outbind_str = commen.outbint(code);
                     returnstr = "{\"result\":\"ok\",\"msg\":\"" + outbind_str + "\"}";
                     break;
                }
              //  commen.log(returnstr);
            }
            catch (Exception ex)
            {
              //  commen.log(returnstr);
                returnstr = "{\"result\":\"error\",\"msg\":\"" + ex.Message + "\"}";
            }
           
            Response.Write(returnstr);
        }


        #region

        /// <summary>
        /// 这个也是转换为json不过是用系统的
        /// </summary>
        /// <param name="dt"></param>
        /// <returns></returns>
        public string DataTableToJson(DataTable dt)
        {
            string result = "";
            result = JsonConvert.SerializeObject(dt, new DataTableConverter());
            //new DataTableConverter()一般是固定的
            return result;
        }
        /// <summary>     
        /// dataTable转换成Json格式     
        /// </summary>     
        /// <param name="dt"></param>     
        /// <returns></returns>     
        public static string tableToJson(DataTable dt, string tablename)
        {
            StringBuilder jsonBuilder = new StringBuilder();
            jsonBuilder.Append("\"");
            jsonBuilder.Append(tablename);
            jsonBuilder.Append("\":[");
            if (dt.Rows.Count > 0)
            {
                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    jsonBuilder.Append("{");
                    for (int j = 0; j < dt.Columns.Count; j++)
                    {
                        jsonBuilder.Append("\"");
                        jsonBuilder.Append(dt.Columns[j].ColumnName.ToLower());
                        jsonBuilder.Append("\":\"");
                        if (dt.Columns[j].DataType == typeof(DateTime))
                        {
                            String v = dt.Rows[i][j].ToString().Trim();
                            if (v != "")
                            {
                                DateTime d = DateTime.Now;
                                DateTime.TryParse(v, out d);
                                v = d.ToString("yyyy-MM-dd HH:mm:ss");
                            }
                            jsonBuilder.Append(v);
                        }
                        else
                        {
                            String v = dt.Rows[i][j].ToString().Trim();
                            v = v.Replace("\"", "\\\"").Replace("\r", "").Replace("\n", "").Replace("\\", "\\\\");
                            jsonBuilder.Append(v);
                        }
                        jsonBuilder.Append("\",");
                    }

                    jsonBuilder.Remove(jsonBuilder.Length - 1, 1);
                    jsonBuilder.Append("},");
                }
            }
            else
            {
                jsonBuilder.Append(",");
            }
            jsonBuilder.Remove(jsonBuilder.Length - 1, 1);

            jsonBuilder.Append("]");
            //jsonBuilder.Append("}");
            return jsonBuilder.ToString();
        }

        /// <summary>
        /// 获取数据流
        /// </summary>
        /// <returns></returns>
        public string getpost()
        {
            string g = "";
            if (HttpContext.Current.Request.InputStream != null)
            {
                System.IO.StreamReader sr = new System.IO.StreamReader(HttpContext.Current.Request.InputStream, System.Text.Encoding.UTF8);
                g = sr.ReadToEnd();
            }
            return g;
        }
        /// <summary>
        /// 从jobject中获取相应的数据 
        /// </summary>
        /// <param name="jobj">jobject对象</param>
        /// <param name="key">要获取的值</param>
        /// <returns></returns>
        public string jobject(JObject jobj, string key)
        {
            string hh = "";
            if (jobj[key] != null)
            {
                hh = jobj[key].ToString().Trim();
            }
            return hh;
        }

        #endregion

        }
}